<?php
namespace app\admin\controller;

use app\BaseController;
use app\model\AdminUser;
use app\validate\AdminUser as AdminUserValide;
use think\exception\ValidateException;

class User extends BaseController
{
    // 登录接口
    public function login()
    {
        $username = input('param.username','');
        $password = sha1(input('param.password',''));
        try{
            validate(AdminUserValide::class)->check([
                'username' => $username,
                'password' => $password,
                'nickname' => '登录校验'
            ]);
        }catch(ValidateException $e){
            return json(['code'=> 500, 'msg'=>$e->getError()]);
        }

        $user = new AdminUser();
        $result = $user->loginUser($username,$password);
        if($result){
            return json(['code'=>200,'data'=> $result,'msg'=>'登录成功！']);
        }
        return json(['code'=>401,'msg'=>'用户名或者账号不正确！']);
    }
    // 生成一个管理员
    public function generateAdminUser(){
        $username = input('param.username','');
        $nickname = input('param.nickname','管理员');
        $password = sha1(md5(input('param.password','12345678')));
        $headimage= input('param.headimage');
        try{
            validate(AdminUserValide::class)->check([
                'username' => $username,
                'password' => $password,
                'nickname' => $nickname
            ]);
        }catch(ValidateException $e){
            return json(['code'=> 500, 'msg'=>$e->getError()]);
        }
        $user = new AdminUser();
        if($user->generateAdmin($username,$password,$nickname,$headimage)){
            return json(['code' => 200 , 'msg' => '创建成功']);
        }
        return json(['code'=>500, 'msg' => '创建失败,用户名可能重复']);
    }
    // 获取个人的基本信息
    public function base(){
        $id = request()->id; // 获取用户的id
        $user = new AdminUser();
        $userHandle = $user->getMyselfProfile($id);
        return $userHandle;
    }
    // 修改管理员的密码
    public function alterPassword(){
        $password = input('param.password','12345678');
        $user_id  = input('param.userid',request()->id);

        $user = new AdminUser();
        return json($user->alterPassword($user_id,$password));
    }
}
